package com.zhongli.devplatform.service.impl.im;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhongli.devplatform.constant.im.TencentIMConstant;
import com.zhongli.devplatform.mapper.im.TencentC2CMessageMapper;
import com.zhongli.devplatform.po.im.TencentC2CMessagePO;
import com.zhongli.devplatform.service.imp.im.CallBackService;
import com.zhongli.devplatform.utils.im.TencentIMUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author WuXiCheng
 * @version 1.0
 */
@Service
@Slf4j
public class CallBackServiceImpl implements CallBackService {

    @Value("${im.sdkAppId}")
    private Long sdkAppId;

    @Autowired
    private TencentC2CMessageMapper tencentC2CMessageMapper;

    @Override
    public Map<String, Object> imCallBackBase(HttpServletRequest request, JSONObject json) {
        Map<String, Object> params = TencentIMUtil.getUrlParams(request);

        Long _sdkAppId_ = Long.parseLong(params.get(TencentIMConstant.SDKAPPID).toString());

        // 检查 SDK APP ID
        if(_sdkAppId_ == null || !sdkAppId.equals(_sdkAppId_)){
            log.error("SDKAppID 不匹配");
            log.error("请求中的SDKAppID:\t", params.get(TencentIMConstant.SDKAPPID));
            log.error("正确的SDKAppID:\t", sdkAppId);
            return TencentIMUtil.buildFailReply("SDKAppId不匹配");
        }

        String CallbackCommand = params.get(TencentIMConstant.CALLBACKCOMMAND).toString();

        switch (CallbackCommand){
            case TencentIMConstant.COMMAND_STATE_CHANGE:
                return stateChange(params, json);
            case TencentIMConstant.COMMAND_FRIEND_ADD:
                return friendAdd(params, json);
            case TencentIMConstant.COMMAND_FRIEND_DEL:
                return friendDel(params, json);
            case TencentIMConstant.COMMAND_BLACKLIST_ADD:
                return blackListAdd(params, json);
            case TencentIMConstant.COMMAND_BLACKLIST_DEL:
                return blackListDel(params, json);
            case TencentIMConstant.COMMAND_C2C_BEFORE_SEND_MSG:
                return C2CBeforeSendMsg(params, json);
            case TencentIMConstant.COMMAND_C2C_AFTER_SEND_MSG:
                return C2CAfterSendMsg(params, json);
            case TencentIMConstant.COMMAND_GROUP_BEFORE_CREATE:
                return groupBeforeCreate(params, json);
            case TencentIMConstant.COMMAND_GROUP_AFTER_CREATE:
                return groupAfterCreate(params, json);
            case TencentIMConstant.COMMAND_GROUP_BEFORE_APPLY_JOIN:
                return groupBeforeApplyJoin(params, json);
            case TencentIMConstant.COMMAND_GROUP_BEFORE_INVITE_JOIN:
                return groupBeforeInviteJoin(params, json);
            case TencentIMConstant.COMMAND_GROUP_AFTER_MEMBER_JOIN:
                return groupAfterMemberJoin(params, json);
            case TencentIMConstant.COMMAND_GROUP_AFTER_MEMBER_EXIT:
                return groupAfterMemberExit(params, json);
            case TencentIMConstant.COMMAND_GROUP_BEFORE_SEND_MSG:
                return groupBeforeSendMsg(params, json);
            case TencentIMConstant.COMMAND_GROUP_AFTER_SEND_MSG:
                return groupAfterSendMsg(params, json);
            case TencentIMConstant.COMMAND_GROUP_AFTER_GROUP_FULL:
                return groupAfterGroupFull(params, json);
            case TencentIMConstant.COMMAND_GROUP_AFTER_DESTROYED:
                return groupAfterDestoryed(params, json);
            case TencentIMConstant.COMMAND_GROUP_AFTER_INFO_CHANGED:
                return groupAfterInfoChanged(params, json);
            default:
                return null;
        }
    }

    /**
     * 状态变更回调 包括
     *      用户上线
     *      用户注销下线或用户网络断开
     *      App 心跳超时(App异常被kill或crash)
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> stateChange(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 添加好友之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> friendAdd(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 删除好友之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> friendDel(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 添加黑名单之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> blackListAdd(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 删除黑名单之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> blackListDel(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 单聊发送消息之前回调
     *      ErrorCode   0 允许发言  1 拒绝发言
     * https://cloud.tencent.com/document/product/269/1632
     * @param params    请求参数
     * @param json      消息内容
     * @return
     */
    private Map<String, Object> C2CBeforeSendMsg(Map<String, Object> params, JSONObject json) {


        Map<String, Object> res = TencentIMUtil.buildOKReply();

        System.out.println(json);

        JSONArray array = new JSONArray();

        JSONObject jo = new JSONObject();

        JSONObject t = new JSONObject();

        t.put("Text", "测试修改文本");

        jo.put("MsgType", "TIMTextElem");
        jo.put("MsgContent", t);

        array.add(jo);

        res.put("MsgBody", array);

        saveMessage(params, json);

        return res;
    }

    /**
     * 发送单聊消息之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> C2CAfterSendMsg(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 创建群组之前回调
     *      ErrorCode 0 允许创建 1 拒绝创建
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupBeforeCreate(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 创建群组之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupAfterCreate(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 申请入群之前回调
     *      ErrorCode   0 允许继续处理加群请求  1 拒绝加群请求
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupBeforeApplyJoin(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 拉人入群之前回调
     *      ErrorCode   0 允许继续处理加群请求
     *      RefusedMembers_Account : ["username", "..."] 拒绝加入的用户列表
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupBeforeInviteJoin(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 新成员入群之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupAfterMemberJoin(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 群成员离开之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupAfterMemberExit(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 群内发言之前回调
     *      ErrorCode   0 允许发言  1 拒绝发言  2 静默丢弃(不会下发该消息，返回发送成功)
     * https://cloud.tencent.com/document/product/269/1619
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupBeforeSendMsg(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 群内发言之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupAfterSendMsg(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 群组满员之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupAfterGroupFull(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 群组解散之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupAfterDestoryed(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }

    /**
     * 群组资料修改之后回调
     * @param params
     * @param json
     * @return
     */
    private Map<String, Object> groupAfterInfoChanged(Map<String, Object> params, JSONObject json) {
        return TencentIMUtil.buildOKReply();
    }



    /**
     * 构建消息对象并存储
     * @param params
     * @param json
     */
    @Async
    protected void saveMessage(Map<String, Object> params, JSONObject json){

        TencentC2CMessagePO c2CMessage = TencentIMUtil.parseC2CMessage(json);

        this.tencentC2CMessageMapper.insert(c2CMessage);

        log.info("save message : " + JSONObject.toJSONString(c2CMessage));
    }
}
